<template>
  <!-- 外协第三步 -->
  <div class="step3 mt-2">
    <div class="top">
      <div class="flexcc left">
        <div class="bold">
          <span>{{ t(`dockRepair.step3`) }}:</span>
          <span>{{ t(`externalAssistance.${store.steplist[2].desc}`) }}</span>
        </div>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="back"
        >
          {{ t(`dockRepair.Back`) }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="handleNext"
        >
          {{ t(`confirmText`) }}
        </el-button>
      </div>
    </div>

    <el-form
      ref="filterFormEl"
      :model="filterData"
      :rules="filterRules"
      label-width="0"
    >
      <div class="filter mt-3">
        <div>
          <el-form-item prop="expectedRepairCountries">
            <el-select-v2
              v-model="filterData.expectedRepairCountries"
              :options="countryOptions"
              :placeholder="t(`externalAssistance.step3page.p1`)"
              clearable
              filterable
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="expectedRepairArea">
            <el-input
              v-model="filterData.expectedRepairArea"
              :placeholder="t(`externalAssistance.step3page.p2`)"
              clearable
            />
          </el-form-item>
        </div>
        <div>
          <el-form-item prop="arrivalTime">
            <el-date-picker
              v-model="filterData.arrivalTime"
              type="date"
              value-format="X"
              :editable="false"
              :placeholder="t(`externalAssistance.step3page.p3`)"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </div>
        <!-- <div>
          <el-form-item prop="ratingStar">
            <el-select
              v-model="filterData.ratingStar"
              class="m-2 wp-100"
              :placeholder="t(`dockRepair.step3page.p4`)"
              clearable
              filterable
            >
              <el-option
                v-for="item in dictData['star_rating']"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </div> -->
        <div>
          <el-form-item prop="quotationEndTime">
            <el-date-picker
              v-model="filterData.quotationEndTime"
              type="datetime"
              value-format="X"
              :editable="false"
              :placeholder="t('dockRepair.step4page.p1')"
              :disabled-date="disabledDate"
              :disabled-hours="disabledHour"
              :disabled-minutes="disabledMinute"
              :default-time="defaultTime"
              format="YYYY-MM-DD HH:mm"
              time-format="HH:mm"
            />
          </el-form-item>
        </div>
      </div>
    </el-form>

    <div
      class="list mt-3"
      v-loading="loading"
    >
      <div
        :class="['item', { active: isActive(item) }]"
        v-for="item in listData"
        :key="item.id"
        @click="itemClick(item)"
      >
        <div
          class="left"
          @click.stop="openShipyard(item)"
        >
          <img :src="item.enterpriseLogo" />
          <div class="num flexcc">
            <div v-if="locale === 'zh-CN'">已服务{{ item.numberOfServices || '0' }}次</div>
            <div v-if="locale === 'en'">Number of times served{{ item.numberOfServices || '0' }}</div>
          </div>
        </div>
        <div class="right">
          <div class="flexsb">
            <div
              class="tit"
              @click.stop="openShipyard(item)"
            >
              <div>{{ item.enterpriseName }}</div>
              <div v-if="locale === 'zh-CN'">{{ item.enterpriseNameCn }}</div>
            </div>
          </div>
          <div class="rate">
            <template v-for="n in 5">
              <img
                src="@/assets/img/icon_shoucang_pre.png"
                alt=""
                v-if="n <= item.ratingStar"
              />
              <img
                src="@/assets/img/icon_shoucang_nor.png"
                alt=""
                v-else
              />
            </template>
          </div>
          <div class="from">{{ item.country }}{{ item.area }}{{ item.address }}</div>
        </div>
        <div class="text">
          {{ item.businessIntroduce }}
        </div>
      </div>
    </div>

    <div class="flexcc mt-3">
      <el-pagination
        layout="prev, pager, next"
        :hide-on-single-page="page.pageNum === 1 && total <= page.pageSize"
        :total="total"
        v-model:current-page="page.pageNum"
        :page-size="page.pageSize"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 通知 -->
    <Notification
      v-if="dialogNotification"
      v-model="dialogNotification"
    />
  </div>
</template>

<script setup>
import { onBeforeMount, reactive, ref, watch, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useExternalAssistance from '@/stores/externalAssistance.js'
import { listPurchaserApi, countryListApi } from '@/service/common.js'
import { debounce } from 'lodash'
import moment from 'moment'
import useDict from '@/hooks/useDict'
import Notification from './Notification.vue' // 通知

const { dictData, getDictData } = useDict()

const router = useRouter()
const route = useRoute()

// onBeforeMount(() => {
//   init()
// })

const { t, locale } = useI18n()

watch(locale, (n) => {
  if (store.activeStep === 2) {
    init()
  }
})

const store = useExternalAssistance()
const { next, back, setInquiryParams } = store

watch(
  () => store.activeStep,
  (n) => {
    if (n === 2 && !listData.value.length) {
      init()
    }
  }
)

//
const dialogNotification = ref(false)

// 下一步
const handleNext = () => {
  if (!filterFormEl.value) return
  filterFormEl.value.validate((valid, fields) => {
    if (valid) {
      if (!checkedList.value.length) {
        ElMessage.warning(t(`externalAssistance.step3page.w1`)) // 请选择外协服务商
        return
      }

      const params = {
        ...filterData.value,
        providerList: checkedList.value
      }

      // console.log(params)
      setInquiryParams(params)
      dialogNotification.value = true
    }
  })
}

// 禁止选择的日期
const disabledDate = (val) => {
  return val.getTime() < Date.now() - 8.64e7
}

/* 限制小时 */
const disabledHour = () => {
  const flag = moment().format('YYYY-MM-DD') === moment.unix(filterData.value.quotationEndTime).format('YYYY-MM-DD')
  if (!flag) return []
  const arrs = []
  for (let i = 0; i < 24; i++) {
    if (new Date().getHours() <= i) continue
    arrs.push(i)
  }
  return arrs
}

/* 限制分 */
const disabledMinute = () => {
  const flag = moment().format('YYYY-MM-DD HH') === moment.unix(filterData.value.quotationEndTime).format('YYYY-MM-DD HH')
  if (!flag) return []
  const arrs = []
  for (let i = 0; i < 60; i++) {
    if (new Date().getMinutes() <= i) continue
    arrs.push(i)
  }
  return arrs
}

// 默认时间
const defaultTime = new Date(2000, 1, 1, new Date().getHours() + 1, 0, 0)

// 筛选对象
const filterFormEl = ref(null)
const filterData = ref({
  expectedRepairCountries: null,
  expectedRepairArea: null,
  arrivalTime: null,
  ratingStar: null
})
const filterRules = reactive({
  expectedRepairCountries: [{ required: true, message: t(`externalAssistance.step3page.r1`), trigger: 'change' }],
  expectedRepairArea: [{ required: false, message: t(`externalAssistance.step3page.r2`), trigger: 'change' }],
  arrivalTime: [{ required: true, message: t(`externalAssistance.step3page.r3`), trigger: 'change' }],
  quotationEndTime: [{ required: true, message: t('dockRepair.step4page.w1'), trigger: 'change' }]
})
watch(
  [() => filterData.value.expectedRepairCountries, () => filterData.value.expectedRepairArea, () => filterData.value.ratingStar],
  debounce(
    (n) => {
      page.value.pageNum = 1
      getList()
    },
    1000,
    {
      leading: false, // 延长开始后调用
      trailing: true // 延长结束前调用
    }
  )
)

// 国家下拉
const countryOptions = ref([])
const getCountry = () => {
  countryListApi().then(({ data }) => {
    countryOptions.value = data.map((r) => {
      return {
        value: r.id,
        label: r.countryName
      }
    })
  })
}

// 外协服务商列表
const listData = ref([])
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 6 // 每页条数
})
const total = ref(0) // 总数
const loading = ref(false)
const getList = () => {
  loading.value = true
  listPurchaserApi(page.value, {
    ...filterData.value,
    registerClassCode: 'waxfws',
    customerClassCode: '11'
  })
    .then(({ data, total: t }) => {
      listData.value = data
      total.value = t
    })
    .finally(() => {
      loading.value = false
    })
}
// 分页
const handleCurrentChange = (val) => {
  // page.value.pageSize = val === 1 ? 4 : 6
  getList()
}

// 勾选的外协商 多选
const checkedList = ref([])
const itemClick = (item) => {
  if (!isActive.value(item)) {
    checkedList.value.push(item)
  } else {
    const i = checkedList.value.findIndex((l) => l.id === item.id)
    checkedList.value.splice(i, 1)
  }
}
const isActive = computed(() => {
  return (item) => {
    return checkedList.value.some((c) => c.id === item.id)
  }
})

//
const openShipyard = ({ id }) => {
  const url = router.resolve({
    path: `/shipyard`,
    query: {
      id
    }
  })
  window.open(url.href)
}

// 初始化
const init = () => {
  getCountry() // 国家
  getDictData('star_rating') // 星级下拉
  getList() // 外协商列表
}
</script>

<style scoped lang="scss">
.step3 {
  padding-bottom: 36px;
  .el-button {
    min-width: 150px;
  }
  .top {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 0px;
    justify-content: space-between;
  }

  .filter {
    background: #fff;
    padding: 24px 114px;
    display: grid;
    grid-template-columns: repeat(2, 500px);
    grid-template-rows: repeat(2, 38px);
    row-gap: 20px;
    column-gap: 30px;

    :deep(.el-select-v2) {
      width: 100%;
      .el-select-v2__wrapper {
        height: 38px;
        line-height: 38px;
      }
    }

    :deep(.el-input__inner) {
      height: 36px;
    }

    :deep(.el-date-editor) {
      width: 100%;
      height: 100%;
      .el-input__wrapper {
        width: 100%;
        height: 100%;
      }
    }
  }

  .list {
    display: grid;
    grid-template-columns: repeat(2, 618px);
    gap: 24px;
    > .item {
      background: #fff;
      padding: 25px;
      display: grid;
      grid-template-columns: 210px auto;
      grid-template-rows: 120px auto;
      gap: 22px;
      border: 4px solid #fff;
      cursor: pointer;
      transition: 0.3s;
      &.active {
        border-color: var(--mainColor);
      }
      .left {
        width: 210px;
        height: 120px;
        position: relative;
        overflow: hidden;
        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: all 0.3s;
        }
        &:hover {
          img {
            transform: scale(1.2);
          }
        }
        .num {
          position: absolute;
          width: 100%;
          padding: 10px 0;
          bottom: 0;
          left: 0;
          background: rgba(37, 38, 40, 0.8);
          color: #fff;
        }
      }
      .right {
        width: 320px;
        height: 120px;
        display: grid;
        grid-template-rows: auto;
        gap: 15px;
        align-content: center;

        .tit {
          transition: 0.3s;
        }

        .from {
          color: #9d9fa5;
          font-size: 12px;
          text-transform: uppercase;
        }

        .rate {
          img {
            margin-right: 5px;
          }
        }
      }
      .text {
        grid-area: 2 / 1 / span 1 / span 2;
        font-size: 12px;
        color: #6a6973;
        line-height: 1.5;
      }
    }
  }
}
</style>
